package com.yitong.spring;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.ReflectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;

public class FastJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
	
	private static class MyValueFilter implements ValueFilter {
		@Override
		public Object process(Object object, String name, Object value) {
			if (value == null && object != null && name != null) {
				Field field = ReflectionUtils.findField(object.getClass(), name);
				if (field == null) {
					return value;
				}
				if (field.getType().isAssignableFrom(Date.class)) {
					return "-";
				} else if (field.getType().isAssignableFrom(String.class)) {
					return "";
				} else if (field.getType().isAssignableFrom(BigDecimal.class) || field.getType().isAssignableFrom(Double.class) || field.getType().isAssignableFrom(Float.class)) {
					return 0.0d;
				} else if (field.getType().isAssignableFrom(Integer.class) || field.getType().isAssignableFrom(Long.class) || field.getType().isAssignableFrom(Short.class)) {
					return 0;
				}
			} else if (value instanceof String && StringUtils.isBlank(value.toString())) {
				return "";
			}
			return value;
		}
	}

	private final static ValueFilter VALUE_FITLER = new MyValueFilter();

	public final static Charset UTF8 = Charset.forName("UTF-8");

	private Charset charset = UTF8;

	private SerializerFeature[] features = new SerializerFeature[0];

	public FastJsonHttpMessageConverter() {
		super(new MediaType("application", "json", UTF8), new MediaType("application", "*+json", UTF8));
		setDefaultFeatures();
	}

	private void setDefaultFeatures() {
		List<SerializerFeature> features = Arrays.asList(SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue);
		this.features = features.toArray(new SerializerFeature[] {});
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		return true;
	}

	public Charset getCharset() {
		return this.charset;
	}

	public void setCharset(Charset charset) {
		this.charset = charset;
	}

	public SerializerFeature[] getFeatures() {
		return features;
	}

	public void setFeatures(SerializerFeature... features) {
		this.features = features;
	}

	@Override
	protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		InputStream in = inputMessage.getBody();
		byte[] buf = new byte[1024];
		for (;;) {
			int len = in.read(buf);
			if (len == -1) {
				break;
			}
			if (len > 0) {
				baos.write(buf, 0, len);
			}
		}
		byte[] bytes = baos.toByteArray();
		return JSON.parseObject(bytes, 0, bytes.length, charset.newDecoder(), clazz);
	}

	@Override
	protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
		OutputStream out = outputMessage.getBody();
		String text = toJSONString(obj);
		byte[] bytes = text.getBytes(charset);
		out.write(bytes);
	}

	public final String toJSONString(Object object, SerializerFeature... features) {
		SerializeWriter out = new SerializeWriter();
		try {
			JSONSerializer serializer = new JSONSerializer(out);
			List<ValueFilter> valueFilters = serializer.getValueFilters();
			valueFilters.add(VALUE_FITLER);
			if (features != null && features.length > 0) {
				for (SerializerFeature feature : features) {
					serializer.config(feature, true);
				}
			}
			for (SerializerFeature feature : this.features) {
				serializer.config(feature, true);
			}
			serializer.write(object);

			return out.toString();
		} finally {
			out.close();
		}
	}
}
